package com.beauty.security;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CookieFilter extends BasicAuthenticationFilter {

    private List<String> ignoreList = new ArrayList();

    public CookieFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
        this.ignoreList.add("register");
        this.ignoreList.add("getNoteList");
        this.ignoreList.add("getNoteDetail");
        this.ignoreList.add("getUserInfo");
        this.ignoreList.add("signIn");
    }


    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        var list = this.ignoreList.stream().filter(u -> request.getRequestURL().toString().lastIndexOf(u) != -1).toList();
        System.out.println(list.size());
        if (list == null || list.size() == 0) {
            if (request.getCookies() != null) {
                var cookieList = Arrays.stream(request.getCookies()).toList();
                var userCookie = cookieList.stream().filter(cookie -> {
                    return cookie.getName().equals("userId");
                }).findFirst();
                if (userCookie.isEmpty()) {
                    response.setStatus(401);
                    return;
                }
            } else {
                response.setStatus(401);
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
